package com.fh.common.interceptors;

import com.fh.entity.po.Org;
import com.fh.mappers.OrgMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


@Component // 将当前类交给ioc管理
public class KuayuInterceptor implements HandlerInterceptor {
    @Autowired
    private OrgMapper orgMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // 处理跨域的  response设置运行跨域
        // 获取请求域
        String origin = request.getHeader("Origin");
        //获取请求的ip
        String ipaddr = request.getRemoteAddr();
        System.out.println(ipaddr);
        List<Org> orgs = (List<Org>) redisTemplate.opsForValue().get("orgData");
        boolean flag = false;
        for (int i = 0; i < orgs.size(); i++) {
            if (ipaddr.equals(orgs.get(i).getName())) {
                flag = true;
                break;
            }
        }

        //判断是否为白名单
        if(flag==true){
            response.setHeader("Access-Control-Allow-Origin",origin);
        }else{ //不在白名单内
            response.setHeader("Access-Control-Allow-Origin",origin);
            //响应错误信息
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            writer.write("{\"code\":3000,\"msg\":\""+ipaddr+" 不在白名单内  如需要 请联系 110，\"}");
        }


        return flag;
    }
}
